/*
 * @Author: t-xiangqun.li t-xiangqun.li@pcitc.com
 * @Date: 2025-10-21 15:31:26
 * @LastEditors: lixiangqun
 * @LastEditTime: 2025-11-15 15:50:49
 * @FilePath: \electrconVue\src\main.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { app, BrowserWindow, ipcMain, protocol, net } from "electron";
import path from "node:path";
import started from "electron-squirrel-startup";
import { CreateChatProps } from "./types";
import fs from "fs/promises";
import OpenAI from "openai";
import "dotenv/config"; // dotenv 模块允许我们将所有的环境变量存储在一个名为 .env 的文件中，并在应用启动时加载这些变量。
import { convertMessage } from "./utils/helper";
import { lookup } from "mime-types";
import url from "node:url";
import { createProvider } from "./provider/createProvider";
// import fs from "node:fs/promises"; // 读图
// import fs from "fs"; // 读文件

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (started) {
  app.quit();
}
protocol.registerSchemesAsPrivileged([
  {
    scheme: "safe-file",
    privileges: { standard: true, secure: true, supportFetchAPI: true },
  },
]);
const createWindow = async () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  protocol.handle("safe-file", async (request) => {
    // 解析地址
    const filePath = decodeURIComponent(
      request.url.slice("safe-file://".length)
    ); // windows解析的地址是：c/Users/15478/AppData/Roaming/electron-ai/images/dog.jpg
    const imageIndex = request.url.lastIndexOf("/");
    const imageName = request.url.substring(imageIndex);
    const userPath = app.getPath("userData");
    const imageDir = path.join(userPath, "images");
    // fs.readFile(filePath), 会定位到E:\vue\electrconVue\c\Users\15478\AppData\Roaming\electron-ai\images\dog.jpg，报错找不到文件
    const data = await fs.readFile(`${imageDir}${imageName}`); //${imageDir}${imageName}对应路径 C:\Users\15478\AppData\Roaming\electron-ai\images/dog.jpg
    return new Response(data, {
      status: 200,
      headers: {
        "Content-Type": lookup(filePath) as string,
        "Content-Length": data.length.toString(), // 为了应对Chromium 对自定义协议的安全检查失败
      },
    });
    // 方法2：
    const newFilePath = url.pathToFileURL(filePath).toString();
    return net.fetch(newFilePath);
  });

  ipcMain.handle("copy-image-to-user-dir", async (event, sourcePath) => {
    const userPath = app.getPath("userData");
    const imageDir = path.join(userPath, "images");
    await fs.mkdir(imageDir, { recursive: true });
    const fileName = path.basename(sourcePath);
    const destPath = path.join(imageDir, fileName);
    await fs.copyFile(sourcePath, destPath);
    return destPath;
  });

  ipcMain.on("start-chat", async (event, data: CreateChatProps) => {
    console.log(data, "main监听");
    const { messages, selectedModel, providerName, messageId } = data;
    const provider = createProvider(providerName);
    const stream = await provider.chat(messages, selectedModel);
    for await (const chunk of stream) {
      const content = {
        messageId,
        data: chunk,
      };
      mainWindow.webContents.send("update-message", content); // 主进程发送事件
    }
  });

  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    mainWindow.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)
    );
  }

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
